<template>
  <el-drawer
    v-model="dialogVisible"
    :title="title"
    direction="rtl"
    size="680px"
    :before-close="handleClose"
    :destroy-on-close="true"
    class="follow-dialog"
    append-to-body
  >
    <div class="dialog-content">
      <!-- 被随访人输入框 -->
      <div class="form-item">
        <div class="label">被随访人</div>
        <el-select
          v-model="formData.userId"
          placeholder="请选择被随访人"
          filterable
          clearable
          style="width: 100%"
        >
          <el-option
            v-for="user in serviceUserList"
            :key="user.userId"
            :label="user.userName"
            :value="user.userId"
          />
        </el-select>
      </div>

      <!-- Tab切换 -->
      <div class="tab-container">
        <el-tabs v-model="activeTab" class="custom-tabs">
          <div v-if="activeTab === 'follow'" class="follow-tip">
            注：当前用户健康分类为：<span>{{ healthCategory }}</span> 建议{{
              suggestedFollowUpPeriod
            }}随访。
          </div>
          <!-- 随访计划tab：创建模式或当前激活tab为follow时显示 -->
          <el-tab-pane
            v-if="props.mode === 'create' || activeTab === 'follow'"
            label="随访计划"
            name="follow"
          >
            <follow-plan
              ref="followPlanRef"
              :key="`follow-${formData.userId}`"
              :user-id="formData.userId"
              :plan-id="taskData?.planId"
              :mode="props.mode"
              @submit="handleFollowPlanSubmit"
            />
          </el-tab-pane>
          <!-- 体检计划tab：创建模式或当前激活tab为check时显示 -->
          <el-tab-pane
            v-if="props.mode === 'create' || activeTab === 'check'"
            label="体检计划"
            name="check"
          >
            <exam-plan
              ref="examPlanRef"
              :key="`exam-${formData.userId}`"
              :user-id="formData.userId"
              :plan-id="taskData?.planId"
              :mode="props.mode"
              @submit="handleExamPlanSubmit"
            />
          </el-tab-pane>
          <!-- 疫苗计划tab：创建模式或当前激活tab为vaccine时显示 -->
          <el-tab-pane
            v-if="props.mode === 'create' || activeTab === 'vaccine'"
            label="疫苗计划"
            name="vaccine"
          >
            <vaccine-plan
              ref="vaccinePlanRef"
              :key="`vaccine-${formData.userId}`"
              :user-id="formData.userId"
              :plan-id="taskData?.planId"
              :mode="props.mode"
              @submit="handleVaccinePlanSubmit"
            />
          </el-tab-pane>
        </el-tabs>
      </div>
    </div>

    <!-- 底部按钮 -->
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">关闭</el-button>
        <el-button
          v-if="!isView"
          type="primary"
          style="margin-left: 10px"
          @click="handleSubmit"
        >
          {{ isEdit ? "保存" : "创建随访计划" }}
        </el-button>
      </div>
    </template>
  </el-drawer>
</template>

<script setup>
import { followApi } from "@/api/follow"; // 导入API
import { useToolsStore } from "@/store/modules/tools";
import { userKey } from "@/utils/auth";
import { storageLocal } from "@pureadmin/utils";
import { ElMessage } from "element-plus";
import { computed, defineEmits, defineProps, onMounted, ref, watch } from "vue";
import ExamPlan from "./examPlan.vue";
import FollowPlan from "./followPlan.vue";
import VaccinePlan from "./vaccinePlan.vue";

const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  },
  taskData: {
    type: Object,
    default: () => ({})
  },
  mode: {
    type: String,
    default: "create", // 默认创建模式
    validator: value => ["create", "edit", "view"].includes(value)
  }
});

const emit = defineEmits(["update:visible", "submit"]);
// 新增：服务用户列表
const serviceUserList = ref([]);
const currentUserId = computed(() => {
  return storageLocal().getItem(userKey).userId;
});
// 获取服务用户列表
const getServiceUsers = async () => {
  try {
    const response = await followApi.getDoctorServiceUsers({
      userId: currentUserId.value
    });
    serviceUserList.value = response.data || [];
  } catch (error) {
    console.error("获取服务用户列表失败:", error);
    serviceUserList.value = [];
  }
};

// 计算标题
const title = computed(() => {
  if (props.mode === "view") {
    return "查看任务计划";
  } else if (props.mode === "edit") {
    return "修改任务计划";
  } else {
    if (activeTab.value === "follow") {
      return "创建随访计划";
    } else if (activeTab.value === "check") {
      return "创建体检计划";
    } else if (activeTab.value === "vaccine") {
      return "创建疫苗计划";
    }
    return "创建任务计划";
  }
});

// 获取store实例
const toolsStore = useToolsStore();

// 获取随访计划条件数据
const followUpPlanCondition = computed(() => {
  return toolsStore.getDictData().followUpPlanCondition || {};
});

// 获取健康分类和建议随访周期
const healthCategory = computed(() => {
  return followUpPlanCondition.value.healthCategoryTagName || "未知";
});

// 计算建议随访周期，兼容plansPeriodList为数组的情况，找到id等于recommendedPlanId的项并返回其name
const suggestedFollowUpPeriod = computed(() => {
  const periodList = Array.isArray(followUpPlanCondition.value.plansPeriodList)
    ? followUpPlanCondition.value.plansPeriodList
    : [];
  const found = periodList.find(
    item => item.id === +followUpPlanCondition.value.recommendedPlanId
  );
  if (found && found.name) {
    return found.name;
  }
  return "每月1次";
});

// 判断是否是编辑模式
const isEdit = computed(() => {
  return props.mode === "edit";
});

// 判断是否是查看模式
const isView = computed(() => {
  return props.mode === "view";
});

// 控制弹窗显示
const dialogVisible = computed({
  get: () => props.visible,
  set: val => emit("update:visible", val)
});

// 将formData改为响应式数据
const formData = ref({
  remark: "",
  userId: props.taskData?.userId || null,
  userName: props.taskData?.userName || ""
});

const getTabByTaskType = taskType => {
  if (taskType === 1) return "follow";
  if (taskType === 2) return "vaccine";
  if (taskType === 3) return "check";
  return "follow"; // 默认随访
};

const activeTab = ref(getTabByTaskType(props.taskData?.taskType));

// 监听 taskData 变化，动态设置 activeTab
watch(
  () => props.taskData?.taskType,
  newTaskType => {
    const newTab = getTabByTaskType(newTaskType);
    activeTab.value = newTab;
  },
  { immediate: true }
);
// 监听 props.taskData 变化，更新 formData
watch(
  () => props.taskData,
  newTaskData => {
    if (newTaskData) {
      formData.value.userId = newTaskData.userId || null;
      formData.value.userName = newTaskData.userName || "";
    }
  },
  { immediate: true, deep: true }
);

// 关闭弹窗
const handleClose = () => {
  dialogVisible.value = false;
};

// 提交表单
// 组件引用
const followPlanRef = ref();
const examPlanRef = ref();
const vaccinePlanRef = ref();

const handleSubmit = async () => {
  if (!formData.value.userId) {
    ElMessage.error("请选择服务用户");
    return;
  }
  try {
    if (activeTab.value === "follow" && followPlanRef.value) {
      await followPlanRef.value.submitForm();
    } else if (activeTab.value === "check" && examPlanRef.value) {
      await examPlanRef.value.submitForm();
    } else if (activeTab.value === "vaccine" && vaccinePlanRef.value) {
      await vaccinePlanRef.value.submitForm();
    } else {
      emit("submit", {
        ...formData.value,
        type: activeTab.value
      });
    }
  } catch (error) {
    console.error("提交失败:", error);
  }
};

// 处理随访计划提交
const handleFollowPlanSubmit = data => {
  console.log("随访计划提交数据:", data);
  dialogVisible.value = false;
};

// 处理体检计划提交
const handleExamPlanSubmit = data => {
  console.log("体检计划提交数据:", data);
  dialogVisible.value = false;
};

// 处理疫苗计划提交
const handleVaccinePlanSubmit = data => {
  console.log("疫苗计划提交数据:", data);
  dialogVisible.value = false;
};
onMounted(() => {
  getServiceUsers();
});
</script>

<style lang="scss">
.follow-dialog {
  // 确保抽屉从右侧出现
  :deep(.el-drawer) {
    direction: initial; // 重置direction，避免CSS direction属性干扰
  }
  .el-drawer__header {
    padding: 16px 20px;
    border-bottom: 1px solid #e4e7ed;
    color: #333;
    margin-bottom: 0;
    .el-drawer__title {
      font-size: 16px;
      font-weight: 500;
    }
  }
  .el-drawer__body {
    padding: 0 !important;
  }

  .dialog-content {
    padding: 20px;
    height: calc(100% - 120px); // 减去header和footer的高度
    overflow-y: auto;

    .form-item {
      margin-bottom: 24px;

      .label {
        font-size: 14px;
        color: #333;
        margin-bottom: 8px;
      }
    }

    .tab-container {
      margin: 24px 0;

      .custom-tabs {
        :deep(.el-tabs__header) {
          margin-bottom: 20px;
        }
      }

      .placeholder {
        height: 300px;
        background: #f5f7fa;
        border-radius: 4px;
        display: flex;
        align-items: center;
        justify-content: center;
        color: #909399;
      }
    }
  }

  .dialog-footer {
    padding: 20px;
    text-align: right;
    border-top: 1px solid #ebeef5;
    position: absolute;
    bottom: 0;
    left: 0;
    right: 0;
    background: #fff;
  }
}
.follow-tip {
  font-size: 12px;
  color: rgba(0, 0, 0, 0.6);
  padding-left: 3px;

  span {
    width: 76px;
    height: 20px;
    padding: 3px;
    background: #ffe281;
    border-radius: 4px;
    font-weight: 500;
    font-size: 12px;
    color: #222222;
  }
}
</style>
